package com.example.weight.householdWaste;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bin.david.form.core.SmartTable;
import com.bin.david.form.core.TableConfig;
import com.bin.david.form.data.CellInfo;
import com.bin.david.form.data.format.bg.BaseCellBackgroundFormat;
import com.bin.david.form.data.format.bg.ICellBackgroundFormat;
import com.bin.david.form.data.style.FontStyle;
import com.bin.david.form.data.table.TableData;
import com.example.weight.config.Config;
import com.example.weight.model.FaultModel;
import com.example.weight.navigation.HouseholdWasteNavActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.weight.R;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FaultRepairListActivity extends AppCompatActivity {

    private String name, listString,factory;

    private List<FaultModel> list;

    private SmartTable table;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fault_repair_list);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        listString = previousIntent.getStringExtra("list");

        TitleBar titleBar = findViewById(R.id.fault_repair_list_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

//        RequestQueue queue = Volley.newRequestQueue(FaultRepairListActivity.this);
//        String url = Config.url + "/shlj/troubleshooting/getList";
//        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
//                new Response.Listener<String>() {
//                    public void onResponse(String response) {
//                        try {
//                            Log.d("zys", response);
//                            JSONObject jsonObject = new JSONObject(response);
//                            if (!jsonObject.isNull("data")) {
//                                JSONArray data = jsonObject.getJSONArray("data");
//
//                                list = new ArrayList<>();
//
//                                for (int i = 0; i < data.length(); i++) {
//                                    JSONObject item = data.getJSONObject(i);
//                                    String id = item.getString("id");
//                                    String system = item.getString("systemName");
//                                    String equipment = item.getString("equipmentName");
//                                    String occurTime = item.getString("timeOfFailure");
//                                    String step = item.getString("stage");
//                                    String description = item.getString("faultDescription");
//                                    String personInCharge = item.getString("personInCharge");
//                                    FaultModel faultModel = new FaultModel(id, system, equipment, occurTime, step, description, personInCharge);
//                                    list.add(faultModel);
//                                }
//
//                                Log.d("zys", list.size()+"");
//
//                                if (list.size() != 0) {
//                                    TextView noRecordText = findViewById(R.id.hhw_faultRepairList_noRecordText);
//                                    noRecordText.setVisibility(View.GONE);
//
//                                    table = findViewById(R.id.hhw_fault_list);
//                                    table.setData(list);
//
//                                    FontStyle textStyle = new FontStyle(60, Color.BLACK);
//                                    Display display = getWindowManager().getDefaultDisplay();
//                                    Point point = new Point();
//                                    display.getSize(point);
//                                    int width = point.x;
//                                    table.getConfig().setMinTableWidth(width);
//                                    table.getConfig().setContentStyle(textStyle);
//                                    table.getConfig().setColumnTitleStyle(textStyle);
//                                    table.getConfig().setTableTitleStyle(textStyle);
//                                    table.getConfig().setShowXSequence(false);
//                                    table.getConfig().setShowYSequence(false);
//                                    table.getConfig().setVerticalPadding(30);
//
//                                    table.getConfig().setContentCellBackgroundFormat(new BaseCellBackgroundFormat<CellInfo>() {     //设置隔行变色
//                                        @Override
//                                        public int getBackGroundColor(CellInfo cellInfo) {
//                                            if(cellInfo.row % 2 == 1) {
//                                                return ContextCompat.getColor(FaultRepairListActivity.this, R.color.tableBackground);
//                                            }else{
//                                                return TableConfig.INVALID_COLOR;
//                                            }
//                                        }
//                                    });
//
//                                    table.getTableData().setOnRowClickListener((TableData.OnRowClickListener<FaultModel>) (column, fault, col, row) -> {
//                                        // 变色
//                                        table.getConfig().setContentCellBackgroundFormat(new ICellBackgroundFormat<CellInfo>() {
//                                            @Override
//                                            public void drawBackground(Canvas canvas, Rect rect, CellInfo cellInfo, Paint paint) {
//                                                if(cellInfo.row==row && cellInfo.col==col){
//                                                    paint.setColor(Color.GRAY);
//                                                } else {
//                                                    if(cellInfo.row%2 == 1) {
//                                                        paint.setColor(Color.parseColor("#d4d4d4"));
//                                                    } else {
//                                                        paint.setColor(Color.WHITE);
//                                                    }
//                                                }
//                                                canvas.drawRect(rect,paint);
//                                            }
//                                            @Override
//                                            public int getTextColor(CellInfo cellInfo) {
//                                                return 0;
//                                            }
//                                        });
//
//                                        AlertDialog builder = new AlertDialog.Builder(FaultRepairListActivity.this)
//                                                .setTitle("确定完善该故障信息吗？")
//                                                .setMessage(fault.toString())
//                                                .setNegativeButton("取消", null)
//                                                .setPositiveButton("删除", (dialog, which) -> {
//                                                    AlertDialog subBuilder = new  AlertDialog.Builder(FaultRepairListActivity.this)
//                                                            .setTitle("确定删除吗？")
//                                                            .setNegativeButton("取消", null)
//                                                            .setPositiveButton("删除", (dialog1, which1) ->
//                                                                    delete(fault.getId()))
//                                                            .show();
//                                                    subBuilder.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(30);
//                                                    subBuilder.getButton(DialogInterface.BUTTON_NEGATIVE).setTextSize(30);
//                                                })
//                                                .setNeutralButton("填写", (dialog, which) -> {
//                                                    Intent intent =new Intent(FaultRepairListActivity.this,
//                                                            FaultRepairAfterActivity.class);
//                                                    intent.putExtra("id", fault.getId());
//                                                    intent.putExtra("system", fault.getSystem());
//                                                    intent.putExtra("equipment", fault.getEquipment());
//                                                    intent.putExtra("step", fault.getStep());
//                                                    intent.putExtra("occurTime", fault.getOccurTime());
//                                                    intent.putExtra("description", fault.getDescription());
//                                                    intent.putExtra("personInCharge", fault.getPersonInCharge());
//                                                    startActivityForResult(intent, 1);
//                                                })
//                                                .show();
//                                        builder.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(30);
//                                        builder.getButton(DialogInterface.BUTTON_NEGATIVE).setTextSize(30);
//                                        builder.getButton(DialogInterface.BUTTON_NEUTRAL).setTextSize(30);
//
//                                        // 自定义弹窗字号
//                                        try {
//                                            //获取mAlert对象
//                                            Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
//                                            mAlert.setAccessible(true);
//                                            Object mAlertController = mAlert.get(builder);
//
//                                            //获取mTitleView并设置大小颜色
//                                            Field mTitle = mAlertController.getClass().getDeclaredField("mTitleView");
//                                            mTitle.setAccessible(true);
//                                            TextView mTitleView = (TextView) mTitle.get(mAlertController);
//                                            mTitleView.setTextSize(30);
//
//                                            //获取mMessageView并设置大小颜色
//                                            Field mMessage = mAlertController.getClass().getDeclaredField("mMessageView");
//                                            mMessage.setAccessible(true);
//                                            TextView mMessageView = (TextView) mMessage.get(mAlertController);
//                                            mMessageView.setTextSize(38);
//                                        } catch (IllegalAccessException e) {
//                                            e.printStackTrace();
//                                        } catch (NoSuchFieldException e) {
//                                            e.printStackTrace();
//                                        }
//                                    });
//                                }
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Toast.makeText(FaultRepairListActivity.this, "error", Toast.LENGTH_SHORT).show();
//            }
//        });
//        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//        queue.add(stringRequest);

        table = findViewById(R.id.hhw_fault_list);
        TextView noRecordText = findViewById(R.id.hhw_faultRepairList_noRecordText);

        if (listString.equals("")) {
            table.setVisibility(View.GONE);
        } else {
            noRecordText.setVisibility(View.GONE);

            list = new ArrayList<>();
            String[] listWithSpace = listString.split(",");
            for (String s : listWithSpace) {
                String[] items = s.split(" ");
                int j = 0;
                list.add(new FaultModel(items[j++], items[j++], items[j++], items[j++], items[j++], items[j++], items[j]));
            }

            FontStyle textStyle = new FontStyle(60, Color.BLACK);
            Display display = getWindowManager().getDefaultDisplay();
            Point point = new Point();
            display.getSize(point);
            int width = point.x;
            table.getConfig().setMinTableWidth(width);
            table.getConfig().setContentStyle(textStyle);
            table.getConfig().setColumnTitleStyle(textStyle);
            table.getConfig().setTableTitleStyle(textStyle);
            table.getConfig().setShowXSequence(false);
            table.getConfig().setShowYSequence(false);
            table.getConfig().setVerticalPadding(30);
            table.getConfig().setContentCellBackgroundFormat(new BaseCellBackgroundFormat<CellInfo>() {     //设置隔行变色
                @Override
                public int getBackGroundColor(CellInfo cellInfo) {
                    if(cellInfo.row % 2 == 1) {
                        return ContextCompat.getColor(FaultRepairListActivity.this, R.color.tableBackground);
                    }else{
                        return TableConfig.INVALID_COLOR;
                    }
                }
            });
            table.setData(list);

            table.getTableData().setOnRowClickListener((TableData.OnRowClickListener<FaultModel>) (column, fault, col, row) -> {
                // 变色
                table.getConfig().setContentCellBackgroundFormat(new ICellBackgroundFormat<CellInfo>() {
                    @Override
                    public void drawBackground(Canvas canvas, Rect rect, CellInfo cellInfo, Paint paint) {
                        if(cellInfo.row==row && cellInfo.col==col){
                            paint.setColor(Color.GRAY);
                        } else {
                            if(cellInfo.row%2 == 1) {
                                paint.setColor(Color.parseColor("#d4d4d4"));
                            } else {
                                paint.setColor(Color.WHITE);
                            }
                        }
                        canvas.drawRect(rect,paint);
                    }
                    @Override
                    public int getTextColor(CellInfo cellInfo) {
                        return 0;
                    }
                });

                AlertDialog builder = new AlertDialog.Builder(FaultRepairListActivity.this)
                        .setTitle("确定完善该故障信息吗？")
                        .setMessage(fault.toString())
                        .setNegativeButton("取消", null)
                        .setPositiveButton("删除", (dialog, which) -> {
                            AlertDialog subBuilder = new  AlertDialog.Builder(FaultRepairListActivity.this)
                                    .setTitle("确定删除吗？")
                                    .setNegativeButton("取消", null)
                                    .setPositiveButton("删除", (dialog1, which1) ->
                                            delete(fault.getId()))
                                    .show();
                            subBuilder.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(30);
                            subBuilder.getButton(DialogInterface.BUTTON_NEGATIVE).setTextSize(30);
                        })
                        .setNeutralButton("填写", (dialog, which) -> {
                            Intent intent =new Intent(FaultRepairListActivity.this,
                                    FaultRepairAfterActivity.class);
                            intent.putExtra("id", fault.getId());
                            intent.putExtra("system", fault.getSystem());
                            intent.putExtra("equipment", fault.getEquipment());
                            intent.putExtra("step", fault.getStep());
                            intent.putExtra("occurTime", fault.getOccurTime());
                            intent.putExtra("description", fault.getDescription());
                            intent.putExtra("personInCharge", fault.getPersonInCharge());
                            intent.putExtra("factory",factory);
                            startActivityForResult(intent, 1);
                        })
                        .show();
                builder.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(30);
                builder.getButton(DialogInterface.BUTTON_NEGATIVE).setTextSize(30);
                builder.getButton(DialogInterface.BUTTON_NEUTRAL).setTextSize(30);

                // 自定义弹窗字号
                try {
                    //获取mAlert对象
                    Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
                    mAlert.setAccessible(true);
                    Object mAlertController = mAlert.get(builder);

                    //获取mTitleView并设置大小颜色
                    Field mTitle = mAlertController.getClass().getDeclaredField("mTitleView");
                    mTitle.setAccessible(true);
                    TextView mTitleView = (TextView) mTitle.get(mAlertController);
                    mTitleView.setTextSize(40);

                    //获取mMessageView并设置大小颜色
                    Field mMessage = mAlertController.getClass().getDeclaredField("mMessageView");
                    mMessage.setAccessible(true);
                    TextView mMessageView = (TextView) mMessage.get(mAlertController);
                    mMessageView.setTextSize(38);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            });
        }

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(view -> {
            Intent intent =new Intent(FaultRepairListActivity.this,
                    FaultRepairActivity.class);
            intent.putExtra("name", name);
            intent.putExtra("factory", factory);
            startActivityForResult(intent, 1);
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String listTemp = data.getStringExtra("list");
            boolean needRefresh = data.getBooleanExtra("needRefresh", true);
            if (needRefresh)
                refresh(listTemp);
        }
    }

    // 刷新activity
    public void refresh(String newListString) {
        finish();
        Intent intent = new Intent(FaultRepairListActivity.this,
                FaultRepairListActivity.class);
        intent.putExtra("name", name);
        intent.putExtra("list", newListString);
        intent.putExtra("factory", factory);
        startActivity(intent);
    }

    public void delete(String id) {
        RequestQueue queue = Volley.newRequestQueue(this);
        String deleteUrl = Config.url + "/shlj/troubleshooting/delete?id="+id + "&factory=" + factory;
        StringRequest deleteRequest = new StringRequest(Request.Method.POST, deleteUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String code = jsonObject.getString("code");

                            if (code.startsWith("2"))
                                Toast.makeText(FaultRepairListActivity.this,
                                        "删除成功", Toast.LENGTH_SHORT).show();
                            else
                                Toast.makeText(FaultRepairListActivity.this,
                                        "删除失败", Toast.LENGTH_SHORT).show();

                            String getListUrl = Config.url + "/shlj/troubleshooting/getList" + "?factory=" + factory;
                            StringRequest getListRequest = new StringRequest(Request.Method.GET, getListUrl,
                                    new Response.Listener<String>() {
                                        public void onResponse(String response) {
                                            try {
                                                JSONObject jsonObject = new JSONObject(response);
                                                if (!jsonObject.isNull("data")) {
                                                    String listString = "";
                                                    JSONArray data = jsonObject.getJSONArray("data");
                                                    for (int i = 0; i < data.length(); i++) {
                                                        JSONObject item = data.getJSONObject(i);
                                                        String id = item.getString("id");
                                                        String system = item.getString("systemName");
                                                        String equipment = item.getString("equipmentName");
                                                        String occurTime = item.getString("timeOfFailure");
                                                        String step = item.getString("stage");
                                                        String description = item.getString("faultDescription");
                                                        String personInCharge = item.getString("personInCharge");
                                                        FaultModel faultModel = new FaultModel(id, system, equipment, occurTime, step, description, personInCharge);
                                                        listString = listString.concat(faultModel.toSplitWithSpace());
                                                        if (i < data.length()-1)
                                                            listString = listString.concat(",");
                                                    }

                                                    refresh(listString);
                                                }
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    Toast.makeText(FaultRepairListActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                            getListRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                            queue.add(getListRequest);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(FaultRepairListActivity.this,
                        "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        deleteRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(deleteRequest);
    }
}